package com.itheim.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheim.mapper.ClazzMapper;
import com.itheim.pojo.Clazz;
import com.itheim.pojo.ClazzQueryParem;
import com.itheim.pojo.PageResult;
import com.itheim.pojo.Student;
import com.itheim.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;

    @Override
    public PageResult page(ClazzQueryParem clazzQueryParem) {
        PageHelper.startPage(clazzQueryParem.getPage(), clazzQueryParem.getPageSize());
        List<Clazz> clazzList = clazzMapper.page(clazzQueryParem);

        for (Clazz clazz : clazzList) {
            if (LocalDate.now().isBefore(clazz.getBeginDate())) {
                clazz.setStatus("未开班");
                continue;
            }
            if (LocalDate.now().isAfter(clazz.getEndDate())) {
                clazz.setStatus("已结课");
                continue;
            }

            clazz.setStatus("在读中");
        }
        Page<Clazz> p = (Page<Clazz>) clazzList;
        return new PageResult<>(p.getTotal(), p.getResult());
    }

    @Override
    public void add(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazz.setCreateTime(LocalDateTime.now());
        clazzMapper.add(clazz);

    }

    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.getinfo(id);
    }

    @Override
    public void update(Clazz clazz) {
        clazzMapper.update(clazz);
    }

    @Override
    public void deletebyId(Integer id) {
        //检查班级里是否有学生
        List<Student> studentList=clazzMapper.checkStudent(id);
        //删除班级
        if (studentList.size()==0){
            clazzMapper.delete(id);
        }else {
            System.out.println(studentList);
            throw new RuntimeException("班级里还有学生，不能删除");
        }
    }

    @Override
    public List<Clazz> list() {
        return clazzMapper.list();
    }

}